package com.imoblife.brainwavestus.customview;


import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Set;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.imoblife.brainwavestus.BrainWavestusApplication;
import com.imoblife.brainwavestus.MainActivity;
import com.imoblife.brainwavestus.R;
import com.imoblife.brainwavestus.model.Constant;
import com.imoblife.brainwavestus.oldDownloadFrame.Commmand;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItem;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItem.DownLoadingListener;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItemPragrame;
import com.imoblife.brainwavestus.oldMedia.MediaplayerFactory;
import com.imoblife.brainwavestus.product.Store;
import com.imoblife.brainwavestus.service.DownLoadSchedulerSystem;
import com.imoblife.brainwavestus.user.User;
import com.imoblife.brainwavestus.util.AlertDialogUtil;
import com.imoblife.brainwavestus.util.BitMapFlyweightFactory;
import com.imoblife.brainwavestus.util.DBUtil;
import com.imoblife.brainwavestus.util.ProductUtil;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.os.Build.VERSION;
import android.os.Handler;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class UserProduct extends BasicDisplay {
	
	private DBUtil mDb;
	private Store mStore;
	private User mUser;
	
	public UserProduct(Activity activity) {
		super(activity);
		productName = mActivity.getIntent().getExtras()
							.getString(Constant.PRODUCT_ID);
		mHashMap = new HashMap<String, UserProduct.UserItemView>();
		
		mDb = new DBUtil(activity);
		BrainWavestusApplication app 
						= (BrainWavestusApplication)activity.getApplication();
		
		mStore = app.getStore();
		mUser = app.getUser();
	}

	private class UserItemView {

		String taskName;
		Button playButton;
		ProgressBar downloadProgressBar;
		TextView downloadinfo;
		View mItemView;
		public int mTaskState;

		public UserItemView(Activity activity, LayoutInflater inflater,
				XmlPullParser parser) throws XmlPullParserException,
				IOException {

			initView(inflater, parser);
			downloadProgressBar = (ProgressBar) mItemView
					.findViewById(R.id.download_progress);
			downloadinfo = (TextView) mItemView
					.findViewById(R.id.download_text);
			playButton = (Button) mItemView.findViewById(R.id.play);

		}

		public View getView() {

			if (DownLoadSchedulerSystem.getDownloadTaskState(taskName
					+ ".music", mActivity) != DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE) {
				updateUI();
				initialAction();
				return mItemView;
			}
			return null;
		}

		protected void initView(LayoutInflater inflater, XmlPullParser xp)
				throws XmlPullParserException, IOException {

			System.out.println("initView");

			if (isXLargerScreen()) {
				mItemView = inflater.inflate(R.layout.tbuseitem, null);
			} else {
				mItemView = inflater.inflate(R.layout.user_brainwave, null);
			}

			for (int i = 0; i < xp.getAttributeCount(); i++) {

				if (xp.getAttributeName(i).equals("brainstate")) {
					TextView brainstate_text = (TextView) mItemView
							.findViewById(R.id.brainstate_text);
					brainstate_text.setText(xp.getAttributeValue(i));
				} else if (xp.getAttributeName(i).equals("description")) {
					TextView description_text = (TextView) mItemView
							.findViewById(R.id.description_text);
					description_text.setText(mActivity.getResources()
							.getString(R.string.description)
							+ xp.getAttributeValue(i));
				} else if (xp.getAttributeName(i).equals("length")) {
					TextView length_text = (TextView) mItemView
							.findViewById(R.id.length_text);
					length_text.setText(xp.getAttributeValue(i));

				} else if (xp.getAttributeName(i).equals("name")) {
					TextView name = (TextView) mItemView
							.findViewById(R.id.name);
					name.setText(xp.getAttributeValue(i));
				} else if ("id".equals(xp.getAttributeName(i))) {
					taskName = xp.getAttributeValue(i);
				} else if ("title".equals(xp.getAttributeName(i))) {
					TextView title = (TextView) mActivity
							.findViewById(R.id.title);
					title.setText(xp.getAttributeValue(i));

				}

			}

		}

		public void updateUI() {

			mTaskState = DownLoadSchedulerSystem.getDownloadTaskState(taskName
					+ ".music", mActivity);

			switch (mTaskState) {
			case DownLoadItemPragrame.DOWN_STATE_END:

				playButton.setText(R.string.play);

				((View) (downloadProgressBar.getParent()))
						.setVisibility(View.GONE);

				break;
			case DownLoadItemPragrame.DOWN_STATE_START: {

				((View) (downloadProgressBar.getParent()))
						.setVisibility(View.VISIBLE);
				playButton.setText(R.string.cancel);
				downloadProgressBar.setMax(100);
				float progress = DownLoadSchedulerSystem.getProgressDownload(
						taskName + ".music", mActivity);
				System.out.println("progress = " + progress);
				String wait = mActivity.getString(R.string.wait);
				downloadinfo.setText((int) progress + "."
						+ ((int) (progress * 100)) % 100 + "%" + "--" + wait);
				downloadProgressBar.setProgress((int) (progress + 0.5));

			}
				break;
			case DownLoadItemPragrame.DOWN_STATE_FAILE: {
				((View) (downloadProgressBar.getParent()))
						.setVisibility(View.VISIBLE);
				playButton.setText(R.string.retry);
				downloadProgressBar.setMax(100);
				float progress = DownLoadSchedulerSystem.getProgressDownload(
						taskName + ".music", mActivity);

							
				int stateExtr = mDb.openForRead().getDownFileRspCode(
								taskName + Constant.MUSIC_FILE_SUFFIX);
				mDb.closeDb();
				
				if (stateExtr == DownLoadItemPragrame.EXTR_FAILE_SDCARDE) {
					downloadinfo.setText((int) progress + "."
							+ ((int) (progress * 100)) % 100 + "%" + "--"
							+ mActivity.getString(R.string.sdcard_error_extr));
				} else if (stateExtr == DownLoadItemPragrame.EXTR_FAILE_NET) {
					downloadinfo.setText((int) progress + "."
							+ ((int) (progress * 100)) % 100 + "%" + "--"
							+ mActivity.getString(R.string.net_error_extr));

				}
				downloadProgressBar.setProgress((int) (progress + 0.5));
				break;
			}
			case DownLoadItemPragrame.DOWN_STATE_CANCEL:
				playButton.setText(R.string.downLoad);
				break;
			}

		}

		private void initialAction() {

			System.out.println("initialAction");

			playButton.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					int taskState = DownLoadSchedulerSystem
							.getDownloadTaskState(taskName + ".music",
									mActivity);

					switch (taskState) {

					case DownLoadItemPragrame.DOWN_STATE_END: {
						Intent intent = new Intent(mActivity,
								MainActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						SharedPreferences preferences = (SharedPreferences) mActivity
								.getSharedPreferences("PlayTask", 0);
						Editor editor = preferences.edit();
						editor.putString(MainActivity.PLAY_TASK_NAME, taskName)
								.commit();
						MainActivity.isStartMusic = 1;
						mActivity.startActivity(intent);

					}
						break;
					case DownLoadItemPragrame.DOWN_STATE_START: {
						((View) (downloadinfo.getParent()))
								.setVisibility(View.GONE);
						playButton.setText(R.string.downLoad);
						Commmand.makeMusicCancalCommand(taskName + ".music",
								mActivity);
					}
						break;

					case DownLoadItemPragrame.DOWN_STATE_FAILE: {
						playButton.setText(R.string.cancel);
						downloadProgressBar.setMax(100);
						float progress = DownLoadSchedulerSystem
								.getProgressDownload(taskName + ".music",
										mActivity);
						System.out.println("progress = " + progress);
						String wait = mActivity.getString(R.string.wait);
						downloadinfo.setText((int) progress + "."
								+ ((int) (progress * 100)) % 100 + "%" + "--"
								+ wait);
						downloadProgressBar.setProgress((int) (progress + 0.5));
						Commmand.makeMusicDownloadCommand(taskName + ".music",
								mActivity);
						((View) (downloadProgressBar.getParent()))
								.setVisibility(View.VISIBLE);
					}
						break;
					case DownLoadItemPragrame.DOWN_STATE_CANCEL: {
						if (Integer.parseInt(VERSION.SDK) < 8) {

							try {
								if (new MediaplayerFactory(mActivity)
										.getBackgoundMediaPlayer().isPlaying()) {
									new AlertDialogUtil(mActivity)
											.showAlertDialog(
													mActivity
															.getResources()
															.getString(
																	R.string.alertutil_title),
													mActivity
															.getResources()
															.getString(
																	R.string.alertutil_content_stopmusic),
													mActivity
															.getResources()
															.getString(
																	R.string.alertutil_dismiss));
									return;
								}
							} catch (Exception e) {
								return;
							}

						}

						playButton.setText(R.string.cancel);
						downloadProgressBar.setMax(100);
						float progress = DownLoadSchedulerSystem
								.getProgressDownload(taskName + ".music",
										mActivity);
						System.out.println("progress = " + progress);
						String wait = mActivity.getString(R.string.wait);
						downloadinfo.setText((int) progress + "."
								+ ((int) (progress * 100)) % 100 + "%" + "--"
								+ wait);
						downloadProgressBar.setProgress((int) (progress + 0.5));
						Commmand.makeMusicDownloadCommand(taskName + ".music",
								mActivity);
						((View) (downloadProgressBar.getParent()))
								.setVisibility(View.VISIBLE);

					}
						break;
					}
				}
			});

		}

	}

	String productName;
	private String taskName;
	private String tag = "UserProduct";
	private String title;
	private HashMap<String, UserItemView> mHashMap;

	public void updatePlayList() {
		Set<String> strings = mHashMap.keySet();
		for (String key : strings) {
			mHashMap.get(key).updateUI();
		}

	}

	UserItemView mRoot;

	public void initInfo() throws IOException, XmlPullParserException {

		ImageView icon = (ImageView) mActivity.findViewById(R.id.icon);

		icon.setImageBitmap(BitMapFlyweightFactory
				.getBitMapFlyweightFactory(mActivity.getAssets())
				.getBitMapFlyweight(productName).getBitmap());

		XmlPullParser parser = Xml.newPullParser();

		InputStream fileInputStream = null;

		fileInputStream = mActivity.getAssets().open(
				"des/" + ProductUtil.getLang() + "/" + productName + ".xml");

		parser.setInput(fileInputStream, "UTF-8");

		while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {

			if (XmlPullParser.START_TAG == parser.getEventType()) {

				if ("brainwave".equals(parser.getName())) {

					mRoot = new UserItemView(mActivity,
							mActivity.getLayoutInflater(), parser);

				} else if ("item".equals(parser.getName())) {
					LinearLayout layout = (LinearLayout) mActivity
							.findViewById(R.id.productItemLayout);
					UserItemView userItemView = new UserItemView(mActivity,
							mActivity.getLayoutInflater(), parser);
					View view = userItemView.getView();
					if (view != null) {
						layout.addView(view);
					}

					mHashMap.put(userItemView.taskName + ".music", userItemView);

				} else if ("manual".equals(parser.getName())) {

					TextView manual = (TextView) mActivity
							.findViewById(R.id.menual_text);
					manual.setText(parser.nextText());
				} else if ("detail".equals(parser.getName())) {
					((TextView) mActivity.findViewById(R.id.detail))
							.setText(parser.nextText());
				}
			}
			parser.next();
		}

		if (mHashMap.size() == 0) {
			LinearLayout layout = (LinearLayout) mActivity
					.findViewById(R.id.productItemLayout);
			layout.addView(mRoot.getView());
			mHashMap.put(mRoot.taskName + ".music", mRoot);
		}
		updatePlayList();
	}

	public void setAction() {

		if (isXLargerScreen()) {
			setXlargeAct();
		} else {
			setNomalAction();
		}

	}

	private void setNomalAction() {

		final FrameLayout frameLayout = (FrameLayout) mActivity
				.findViewById(R.id.swich_view_flipper);

		TextView introduction_enter = (TextView) mActivity
				.findViewById(R.id.introduction_enter);
		TextView purchase_enter = (TextView) mActivity
				.findViewById(R.id.playlist);
		TextView guarantee_enter = (TextView) mActivity
				.findViewById(R.id.manual);

		introduction_enter.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				frameLayout.getChildAt(0).setVisibility(View.VISIBLE);
				frameLayout.getChildAt(1).setVisibility(View.GONE);
				frameLayout.getChildAt(2).setVisibility(View.GONE);
			}
		});

		purchase_enter.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				frameLayout.getChildAt(1).setVisibility(View.VISIBLE);
				frameLayout.getChildAt(0).setVisibility(View.GONE);
				frameLayout.getChildAt(2).setVisibility(View.GONE);
			}
		});

		guarantee_enter.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				frameLayout.getChildAt(2).setVisibility(View.VISIBLE);
				frameLayout.getChildAt(0).setVisibility(View.GONE);
				frameLayout.getChildAt(1).setVisibility(View.GONE);
			}
		});

	}

	private void setXlargeAct() {

		RadioGroup swichGroup = (RadioGroup) mActivity
				.findViewById(R.id.tab_swich);
		swichGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(RadioGroup group, int checkedId) {

				if (checkedId == R.id.radio_ins) {
					mActivity.findViewById(R.id.detail).setVisibility(
							View.VISIBLE);
					mActivity.findViewById(R.id.menual_text).setVisibility(
							View.GONE);

				} else {
					mActivity.findViewById(R.id.detail)
							.setVisibility(View.GONE);
					mActivity.findViewById(R.id.menual_text).setVisibility(
							View.VISIBLE);
				}

			}
		});

	}

	public void registerDownloadingListener() {

		class LibListenerDownload implements DownLoadingListener, Runnable {

			Handler handler = new Handler();
			UserItemView userItemView;
			int extr;
			long progress;
			long size;
			int count = 0;
			boolean isUpdate = false;

			public void run() {

				if (extr == DownLoadItemPragrame.EXTR_SUCC) {

					if (userItemView.mTaskState == DownLoadItemPragrame.DOWN_STATE_FAILE) {
						userItemView.updateUI();
					}

					if (count % 10 == 0) {

						// DebugTool.error(tag, userItemView.taskName+" size=" +
						// size + " progress="
						// + progress);

						userItemView.downloadProgressBar
								.setMax((int) (size / 100));
						userItemView.downloadProgressBar
								.setProgress((int) (progress / 100));

						float fomart = progress * 1.0f / size * 10000f;

						String sub = null;

						if ((int) (fomart % 100) >= 10) {
							sub = (int) (fomart % 100) + "%";
						} else {
							sub = "0" + (int) (fomart % 100) + "%";
						}
						userItemView.downloadinfo.setText((int) (progress
								* 1.0f / size * 100f)
								+ "." + sub);
					}
					count++;

					if (progress == size) {
						count = 0;
						handler.postDelayed(new Runnable() {
							public void run() {
								updatePlayList();
							}
						}, 200);
					}
				} else {
					count = 0;
					handler.postDelayed(new Runnable() {
						public void run() {
							updatePlayList();
						}
					}, 200);
				}
			}

			public void downloading(String downlaodname, int extr,
					long progress, long size) {
				userItemView = mHashMap.get(downlaodname);
				if (userItemView == null) {
					return;
				}
				this.extr = extr;
				this.progress = progress;
				this.size = size;
				handler.post(this);
			}

		}
		DownLoadItem.setDownLoadingListener(new LibListenerDownload());
	}

	public void unRegisterDownloadingListener() {
		DownLoadItem.setDownLoadingListener(null);
	}

	public void release() {
		BitMapFlyweightFactory.getBitMapFlyweightFactory(mActivity.getAssets())
				.requestRelease(productName);
	}

}
